import {getMenus, getToken} from "@/utils/storage";
import {playAudio} from "@/utils/audio";
import {API} from "@/aconst/API";
import {Notification} from 'element-ui';
import $K from "@/utils/kit";

export let socketData: any = {token: "", type: "", param: {}};
let webSocket: any = null;


//数据接收
export const wsGetMessage = (res: any) => {
    if (!res || !res.data || !JSON.parse(res.data).data) {
        return;
    }
    let data: any = JSON.parse(res.data).data;
    ////console.log("数据接收 data  ", JSON.stringify(data));


    //新增需求审批
    if (data.type == "demand") {
        playAudio(API.audioRequireApproval);
        let notification = Notification({
            title: data.title,
            message: "点击前往查看",
            duration: 0,
            onClick: () => {
                $K.to("/demand/approval", {queryId: data.id});
                notification.close();
            }
        });
    }

    //个人认证信息审批
    if (data.type == "user") {
        playAudio(API.audioPeopleApproval);
        let notification = Notification({
            title: data.title,
            message: "点击前往查看",
            duration: 0,
            onClick: () => {
                $K.to("/supplier/user/approval", {queryId: data.id});
                notification.close();
            }
        });
    }


    //App发布应用通知
    if (data.type == "application") {
        playAudio(API.audioApplicationApproval);
        let notification = Notification({
            title: data.title,
            message: "点击前往查看",
            duration: 0,
            onClick: () => {
                $K.to("/provide/approval", {queryId: data.id});
                notification.close();
            }
        });
    }

};

//初始化WebSocket
export const initWebSocket = () => {
    try {
        //console.log("初始化weosocket  " + WS_URL);
        // webSocket = new WebSocket(WS_URL);
        // webSocket.onmessage = wsGetMessage;
        // webSocket.onopen = wsOpen;
        // webSocket.onerror = wsError;
        // webSocket.onclose = wsClose;
    } catch (e) {
        //console.log("初始化weosocket 失败......");
    }
};

//连接建立之后执行send方法发送数据
export const wsOpen = (actions: any) => {
    //console.log("连接建立之后执行send方法发送数据", actions);
    socketData.token = getToken();
    // socketData.type = "admin";
    // socketData.param = {};
    wsSendMessage(JSON.stringify(socketData));
};

//销毁完成
export const destroyed = () => {
    ////console.log("销毁完成");
    //离开路由之后断开websocket连接
    webSocket.close()
};


//连接建立失败重连
export const wsError = () => {
    //登陆中失败重连
    if (getToken() && getMenus().length != 0) {
        initWebSocket();
    }
};


//数据发送
export const wsSendMessage = (data: any) => {
    //////console.log("wsSendMessage", JSON.parse(data));
    webSocket.send(data);
};

//关闭
export const wsClose = (obj: any) => {
    //////console.log('断开连接', obj);
    initWebSocket();
};

